package com.kili.recommend.data;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class Init {

    private static final Logger LOGGER = LoggerFactory.getLogger(Init.class);

    public static void main(String[] args) {
        generateByTables();
    }

    private static void generateByTables() {
        //项目主包
        String packageName = "com.kilimall.recommend.data";
        //代码生成位置
        String outputDir = "D:\\generator\\kilimall-recommend\\src\\main\\java";
        //需要忽略的表前缀（主要体现在JAVA代码中）
        String[] tablePrefix = {"kilimall_"};
        //需要忽略的列前缀（主要体现在JAVA代码中）
        String[] fieldPrefix = {};
        String[] tableNames = {
                "kilimall_events",
                "kilimall_recommend",
                "kilimall_user"
        };
        LOGGER.info("表总数={}", tableNames.length);
        //user -> UserService, 设置成true: user -> IUserService
        boolean serviceNameStartWithI = false;
        GlobalConfig config = new GlobalConfig();
        String dbUrl = "jdbc:mysql://127.0.0.1/sensors?serverTimezone=UTC&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&allowMultiQueries=true";
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setUrl(dbUrl)
                .setUsername("root")
                .setPassword("root").setDriverName("com.mysql.cj.jdbc.Driver");
        StrategyConfig strategyConfig = new StrategyConfig();
        /*List<TableFill> tableFillList = new ArrayList<>();
        tableFillList.add(new TableFill("create_id", FieldFill.INSERT));
        tableFillList.add(new TableFill("create_time", FieldFill.INSERT));
        tableFillList.add(new TableFill("update_id", FieldFill.UPDATE));
        tableFillList.add(new TableFill("update_time", FieldFill.UPDATE));*/
        strategyConfig
                .setEntityTableFieldAnnotationEnable(true)
                .setCapitalMode(true)//是否大写命名
                .setEntityLombokModel(true)//启用不生成get set
//                .setTableFillList(tableFillList)//自动填充字段
//                .setSuperControllerClass("BaseController")//controlle基础父类
                .setNaming(NamingStrategy.underline_to_camel)//下划线转驼峰
                .setInclude(tableNames)//生成那些表
                .setRestControllerStyle(true)
                .setEntityColumnConstant(true)
                .setTablePrefix(tablePrefix)
                .setFieldPrefix(fieldPrefix);//采用restController
        config.setActiveRecord(false)
                .setDateType(DateType.ONLY_DATE)//使用java.entity.Date
                .setSwagger2(false)//使用swagger2动态接口文档
                .setAuthor("fenny")
                .setOutputDir(outputDir)//存放路径
                .setFileOverride(true)
        ;//生成并覆盖
        if (!serviceNameStartWithI) {
            config.setServiceName("%sService");//service后缀
        }
//        config.setEntityName("%sEntity");//实体后缀


        // 注入自定义配置，可以在 VM 中使用 cfg.abc 【可无】  ${cfg.abc}
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor());
                this.setMap(map);
            }
        };

        // 自定义 xxListIndex.html 生成
        /*List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        focList.add(new FileOutConfig("templates/entity.js.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return "D:\\generator\\entityjs\\prisoner\\" + toLowerCaseFirstOne(tableInfo.getEntityName()) + ".js";
            }
        });
        cfg.setFileOutConfigList(focList);*/

       /* TemplateConfig tc = new TemplateConfig();
        tc.setController("/templates/controller.java");
        tc.setService("/templates/service.java");f
        tc.setServiceImpl("/templates/serviceImpl.java");
        tc.setEntity("templates/entity.java");
        tc.setMapper("/templates/mapper.java");
        tc.setXml("/templates/mapper.xml");*/
        new AutoGenerator().setGlobalConfig(config).setTemplateEngine(new FreemarkerTemplateEngine())
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setCfg(cfg)
                .setPackageInfo(
                        new PackageConfig()
                                .setParent(packageName)
                                .setEntity("entity")
                ).execute();
    }

}
